const { success, badRequest, notFound, error } = require('../utils/response');
const orderModel = require('../models/orderModel');
const cartModel = require('../models/cartModel');

const createOrder = async (req, res) => {
  try {
    const { address } = req.body;
    
    if (!address) {
      return badRequest(res, 'Please provide delivery address');
    }
    
    // 获取购物车中的商品
    const cartItems = await cartModel.getCartByUserId(req.userId);
    if (cartItems.length === 0) {
      return badRequest(res, 'Cart is empty');
    }
    
    // 计算总金额
    const totalAmount = cartItems.reduce((sum, item) => {
      return sum + (item.price * item.quantity);
    }, 0);
    
    // 准备订单项
    const orderItems = cartItems.map(item => ({
      product_id: item.product_id,
      quantity: item.quantity,
      price: item.price
    }));
    
    // 创建订单
    const orderId = await orderModel.createOrder(req.userId, orderItems, totalAmount, address);
    
    // 获取订单详情
    const order = await orderModel.getOrderDetails(orderId, req.userId);
    
    success(res, order, 'Order created successfully');
  } catch (err) {
    error(res, err.message);
  }
};

const getOrders = async (req, res) => {
  try {
    const orders = await orderModel.getOrdersByUserId(req.userId);
    success(res, orders);
  } catch (err) {
    error(res, err.message);
  }
};

const getOrder = async (req, res) => {
  try {
    const order = await orderModel.getOrderDetails(req.params.id, req.userId);
    if (!order) {
      return notFound(res, 'Order not found');
    }
    success(res, order);
  } catch (err) {
    error(res, err.message);
  }
};

module.exports = {
  createOrder,
  getOrders,
  getOrder
};